﻿using System;
using System.Collections.Generic;
using System.Data.EntityClient;
using System.Data.Objects;
using System.Linq;
using System.Transactions;
using System.Data.Entity;

namespace ASPItalia.ModelVirtualCasting.EntityFramework.Wrappers
{
	public class ContextWrapper : IContextWrapper, IDisposable
	{
		ModelVirtualCastingEntities _context;

		public ContextWrapper(ModelVirtualCastingEntities context)
		{
			_context = context;
		}

		public void ChangeObjectState(object entity, System.Data.EntityState state)
		{
			_context.Entry(entity).State = state;
		}

		public void SaveChanges(List<EntityCommand> commands, bool createNewContextAfterSaveChanges)
		{
			if (commands.Any())
			{
				using (TransactionScope scope = new TransactionScope())
				{
					_context.Database.Connection.Open();

					commands.ForEach(c =>
					{
						c.Connection = (EntityConnection)_context.Database.Connection;
						c.ExecuteNonQuery();
					});

					_context.SaveChanges();
					scope.Complete();
				}
			}
			else
			{
				_context.SaveChanges();
			}

			if (createNewContextAfterSaveChanges)
			{
				_context = new ModelVirtualCastingEntities(Configuration.ConnectionString);
			}
		}

		public bool EnableLazyLoading
		{
			get { return _context.Configuration.LazyLoadingEnabled; }
			set { _context.Configuration.LazyLoadingEnabled = value; }
		}

		public DbSet<T> CreateDbSet<T>() where T : class
		{
			return _context.Set<T>();
		}

		public void Dispose()
		{
			_context.Dispose();
		}
	}
}